package com.mxun.winefox.stt

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import android.widget.Toast
import androidx.compose.runtime.mutableStateOf
import java.util.*

class VoiceRecognizerHelper(
    private val context: Context, // 保留context参数
    private val onResult: (String) -> Unit
) {
    val isRecording = mutableStateOf(false)
    private val speechRecognizer: SpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(context)

    // 内部使用Toast的函数，避免在回调中直接访问context
    private fun showToast(message: String) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
    }

    init {
        speechRecognizer.setRecognitionListener(object : RecognitionListener {
            override fun onResults(results: Bundle?) {
                val resultText = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull()
                if (resultText != null) {
                    onResult(resultText)
                } else {
                    showToast("未识别到语音")
                }
                isRecording.value = false
            }

            override fun onError(error: Int) {
                showToast("语音识别失败: $error")
                isRecording.value = false
            }

            override fun onReadyForSpeech(params: Bundle?) {
                // 可选：显示提示
            }

            override fun onBeginningOfSpeech() {}

            override fun onRmsChanged(rmsdB: Float) {}

            override fun onBufferReceived(buffer: ByteArray?) {}

            override fun onEndOfSpeech() {
                // 自动停止识别
                speechRecognizer.stopListening()
            }

            override fun onPartialResults(partialResults: Bundle?) {}

            override fun onEvent(eventType: Int, params: Bundle?) {}
        })
    }

    fun startListening() {
        try {
            val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
                putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
                putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.CHINESE.language) // 强制中文
                putExtra(RecognizerIntent.EXTRA_PROMPT, "请开始说话...")
                putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
            }
            isRecording.value = true
            speechRecognizer.startListening(intent)
        } catch (e: Exception) {
            showToast("语音识别不可用: ${e.message}")
            isRecording.value = false
        }
    }

    fun stopListening() {
        try {
            speechRecognizer.stopListening()
            // 等待识别结果的回调来更新状态
        } catch (e: Exception) {
            showToast("停止录音失败: ${e.message}")
            isRecording.value = false
        }
    }

    fun destroy() {
        try {
            speechRecognizer.destroy()
        } finally {
            isRecording.value = false
        }
    }
}